package com.ihome.android.academy.service;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ihome.android.EAApp;
import com.ihome.android.analytic.JsonAnalytic;
import com.ihome.android.common.ComParams;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.dl.core.DownloadHelper;
import com.ihome.android.dl.core.DownloadManager;
import com.ihome.android.dl.core.DownloadReceiver;
import com.ihome.android.dl.core.DownloadTask;
import com.ihome.android.dl.util.DLFileInfo;
import com.ihome.android.dl.util.DownloadValues;
import com.ihome.android.http.HttpActions;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.market2.aidl.AppOperateAidl;
import com.ihome.android.market2.info.AppDetailInfo;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.info.AppOperateReqInfo;
import com.ihome.android.market2.info.CertificateInfo;
import com.ihome.android.market2.info.DownloadAppInfo;
import com.ihome.android.mod.LoginMod;
import com.ihome.android.util.AppMgr;
import com.ihome.android.util.AppUtils;
import com.ihome.android.util.BgInstallApk;
import com.ihome.android.util.Confirmation;
import com.ihome.android.util.Tools;
import com.ihome.android.util.exception.ITVException;
import com.ihome.android.util.log.LogUtil;
//import com.sun.istack.internal.FinalArrayList;

public class AppOperate extends Service {
	private final String			TAG					= AppOperate.class.getSimpleName();

	private List<AppOprateSynObj>	mAppOprateSynList	= new ArrayList<AppOprateSynObj>();
	/** 下载监听广播接收器 */
	private DownloadReceiver		mReceiver			= null;

	AppOperateAidl.Stub				binder				= new AppOperateAidl.Stub() {

															@Override
															public String appOperate(String reqParam) throws RemoteException {
																AppOprateSynObj appOprateSynObj = null;
																String appPkgName = Confirmation.getProcessNameByPID(AppOperate.this, Binder.getCallingPid());
																boolean isInList = false;
																for (AppOprateSynObj appSynObj : mAppOprateSynList) {
																	if (appSynObj.getPkgName().equals(appPkgName) && appSynObj.getPid() == Binder.getCallingPid()) {
																		isInList = true;
																		appOprateSynObj = appSynObj;
																		break;
																	}
																}
																if (!isInList) {
																	appOprateSynObj = new AppOprateSynObj();
																	appOprateSynObj.setPid(Binder.getCallingPid());
																	appOprateSynObj.setPkgName(appPkgName);
																	mAppOprateSynList.add(appOprateSynObj);
																}

																return appopreate(reqParam, appOprateSynObj);
															}

															@Override
															public boolean appUpdateCheck() throws RemoteException {
																AppOprateSynObj appOprateSynObj = null;
																String appPkgName = Confirmation.getProcessNameByPID(AppOperate.this, Binder.getCallingPid());
																boolean isInList = false;
																for (AppOprateSynObj appSynObj : mAppOprateSynList) {
																	if (appSynObj.getPkgName().equals(appPkgName) && appSynObj.getPid() == Binder.getCallingPid()) {
																		isInList = true;
																		appOprateSynObj = appSynObj;
																		break;
																	}
																}
																if (!isInList) {
																	appOprateSynObj = new AppOprateSynObj();
																	appOprateSynObj.setPid(Binder.getCallingPid());
																	appOprateSynObj.setPkgName(appPkgName);
																	mAppOprateSynList.add(appOprateSynObj);
																}
																return appupdatecheck(appOprateSynObj);
															}

														};

	private Handler					mHandler;

	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				DownloadTask task = (DownloadTask) msg.obj;
				switch (msg.what) {
				case DownloadValues.Types.ADD:

					LogUtil.d(TAG, "---procHandler() Types.ADD ----> FileName = " + task.getAppInfo().getFileName());

					break;
				case DownloadValues.Types.START:
					break;
				case DownloadValues.Types.COMPLETE:
					LogUtil.d(TAG, "---procHandler() Types.COMPLETE ----> FileName = " + task.getAppInfo().getFileName());
					handleCompletedAction(task.getAppInfo());
					break;
				case DownloadValues.Types.PROCESS:
					String speed = task.getDownloadSpeed() + "kbps | " + Tools.formateFileSize(getApplication(), task.getDownloadSize()) + " / "
							+ Tools.formateFileSize(getApplication(), task.getTotalSize());
					String progress = task.getDownloadPercent() + "";
					LogUtil.d(TAG, "---procHandler() Types.PROCESS ---->  " + task.getAppInfo().getFileName() + "  ---> speed = " + speed + "; progress = " + progress);
					handleProgress(task.getAppInfo());

					break;
				case DownloadValues.Types.ERROR:
					handleError(task.getAppInfo(), task.getErrorCode(), task.getErrorInfo());
					break;
				}
			}
		};
	}

	@Override
	public IBinder onBind(Intent intent) {
		LogUtil.i(TAG, "appopreate ----onBind()----");
		return binder;
	}

	public void onCreate() {
		procHandler();
		//startDLReceiver();
		EAApp.getApp().addHandler(mHandler);
	};

	public int onStartCommand(Intent intent, int flags, int startId) {
		LogUtil.i(TAG, " --> onStartCommand flags = " + flags + ", startId = " + startId);

		return super.onStartCommand(intent, flags, startId);
	};

	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		EAApp.getApp().clearHandler(mHandler);
		if (mReceiver != null)
			unregisterReceiver(mReceiver);
	}

	//	/**
	//	 * 启动下载监听广播
	//	 */
	//	private void startDLReceiver() {
	//		LogUtil.d(TAG, "startDLReceiver() -->  ");
	//
	//		if (null == mReceiver) {
	//			mReceiver = new DownloadReceiver();
	//			initDLReceiver();
	//			IntentFilter filter = new IntentFilter();
	//			filter.addAction(DownloadValues.Actions.BROADCAST_RECEIVER_ACTION);
	//			registerReceiver(mReceiver, filter);
	//		}
	//	}
	//
	//	/**
	//	 * 初始化下载监听广播
	//	 */
	//	private void initDLReceiver() {
	//		LogUtil.d(TAG, "initDLReceiver() -->  ");
	//		mReceiver.setDownloadListener(new DownloadListener() {
	//
	//			@Override
	//			public void handleAddAction(DLFileInfo dLFileInfo, Intent intent, boolean isPaused) {
	//				LogUtil.d(TAG, "Add New Download Task --> " + dLFileInfo.getFileName());
	//			}
	//
	//			@Override
	//			public void handleCompletedAction(final DLFileInfo dLFileInfo, Intent intent) {
	//				LogUtil.d(TAG, "Download Completed ---> " + dLFileInfo.getFileName());
	//				String apkPath = dLFileInfo.getFilePath() + dLFileInfo.getFileName();
	//				LogUtil.v(TAG, "apkPath = " + apkPath);
	//				boolean chmodRusult = BgInstallApk.excuteShellComm("chmod 777 " + apkPath);
	//				LogUtil.d(TAG, "chmodRusult = " + chmodRusult);
	//
	//				boolean installResult = BgInstallApk.installAppInBackGround(apkPath, "-r");
	//				LogUtil.v(TAG, "installResult = " + installResult);
	//
	//				String oprateResult = "";
	//				if (installResult) {
	//					//LogUtil.v(TAG, "installationCheck --> Delete APK = " + new File(apkPath).delete());
	//					oprateResult = "{code:0, description: " + getString(R.string.app_install_success) + "}";
	//				}
	//				else {
	//					oprateResult = "{code:-1, description: " + getString(R.string.app_install_success) + "}";
	//				}
	//
	//				new Thread() {
	//					public void run() {
	//						AppOprateSynObj appOprateSynObj = null;
	//						for (AppOprateSynObj appSynObj : mAppOprateSynList) {
	//							if (appSynObj.getPkgName().equals(dLFileInfo.getPkgName())) {
	//								appOprateSynObj = appSynObj;
	//								break;
	//							}
	//						}
	//
	//						if (appOprateSynObj != null) {
	//							synchronized (appOprateSynObj) {
	//								// 处理完成，唤醒等待的同步对象
	//								appOprateSynObj.notifyAll();
	//							}
	//						}
	//					};
	//				}.start();
	//
	//				AppOprateSynObj appOprateSynObj = null;
	//				for (AppOprateSynObj appSynObj : mAppOprateSynList) {
	//					if (appSynObj.getPkgName().equals(dLFileInfo.getPkgName())) {
	//						appOprateSynObj = appSynObj;
	//						break;
	//					}
	//				}
	//
	//				if (appOprateSynObj != null) {
	//					appOprateSynObj.setOprateResult(oprateResult);
	//					if (appOprateSynObj.isNeedUpdate() && installResult) {
	//						final AppInfo appInfo = AppMgr.getInstance().loadAppByPkgName(getApplicationContext(), appOprateSynObj.getPkgName());
	//						LogUtil.d(TAG, "PkgName = " + appOprateSynObj.getPkgName());
	//						AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext(), R.style.AlterDialog);
	//						builder.setTitle(getString(R.string.app_name));
	//						builder.setMessage(getString(R.string.app_upgrade_success, appInfo.getAppName()));
	//						builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
	//							@Override
	//							public void onClick(DialogInterface dialog, int which) {
	//								AppUtils.openApp(getApplicationContext(), appInfo.getPkgName());
	//							}
	//						});
	//						builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
	//							@Override
	//							public void onClick(DialogInterface dialog, int which) {}
	//						});
	//						AlertDialog ad = builder.create();
	//						ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
	//						ad.setCanceledOnTouchOutside(true);
	//						ad.show();
	//					}
	//
	//				}
	//
	//			}
	//
	//			@Override
	//			public void handleProgress(DLFileInfo dLFileInfo, Intent intent) {}
	//		});
	//	}

	public void handleAddAction(DLFileInfo dLFileInfo, boolean isPaused) {
		LogUtil.d(TAG, "Add New Download Task --> " + dLFileInfo.getFileName());
	}

	public void handleCompletedAction(final DLFileInfo dLFileInfo) {
		LogUtil.d(TAG, "Download Completed ---> " + dLFileInfo.getFileName());
		String apkPath = dLFileInfo.getFilePath() + dLFileInfo.getFileName();
		LogUtil.v(TAG, "apkPath = " + apkPath);
		Object[] chmodRusult = BgInstallApk.excuteShellComm("chmod 777 " + apkPath);
		LogUtil.d(TAG, "chmodRusult = " + ((Boolean)chmodRusult[0]).booleanValue());

		Object[] installRst = BgInstallApk.installAppInBackGround(apkPath, "-r");
		LogUtil.v(TAG, "installResult = " + ((Boolean)installRst[0]).booleanValue());

		String oprateResult = "";
		boolean installResult = ((Boolean)installRst[0]).booleanValue();
		if (installResult == true) {
			//LogUtil.v(TAG, "installationCheck --> Delete APK = " + new File(apkPath).delete());
			oprateResult = "{code:0, description: " + getString(R.string.app_install_success) + "}";
		}
		else {
			String errStr = (String)installRst[1];
			if(errStr.contains("INSUFFICIENT_STORAGE")){
				oprateResult = "{code:-1, description: " + getString(R.string.app_install_failure_lackspace) + "}";
			}else if(errStr.contains(ComParams.ERROR_INVALID_PARAMETER)){
				oprateResult = "{code:-1, description: " + getString(R.string.app_install_failure_invalid_para) + "}";
			}else{
				oprateResult = "{code:-1, description: " + getString(R.string.app_install_failure) + "}";
			}
		}
		new Thread() {
			public void run() {
				AppOprateSynObj appOprateSynObj = null;
				for (AppOprateSynObj appSynObj : mAppOprateSynList) {
					if (appSynObj.getPkgName().equals(ConfigUtil.MINSHENG_KEY) || appSynObj.getPkgName().equals(dLFileInfo.getPkgName())) {
						appOprateSynObj = appSynObj;
						break;
					}
				}
				if (appOprateSynObj != null) {
					synchronized (appOprateSynObj) {
						// 处理完成，唤醒等待的同步对象
						appOprateSynObj.notifyAll();
						//gy:从列表中删除
						mAppOprateSynList.remove(appOprateSynObj);
					}
				}
			};
		}.start();

		AppOprateSynObj appOprateSynObj = null;
		for (AppOprateSynObj appSynObj : mAppOprateSynList) {
			if (appSynObj.getPkgName().equals(ConfigUtil.MINSHENG_KEY) || appSynObj.getPkgName().equals(dLFileInfo.getPkgName())) {
				appOprateSynObj = appSynObj;
				break;
			}
		}
		if (appOprateSynObj != null) {
			appOprateSynObj.setOprateResult(oprateResult);
			if (appOprateSynObj.isNeedUpdate() && installResult) {
				final AppInfo appInfo = AppMgr.getInstance().loadAppByPkgName(getApplicationContext(), appOprateSynObj.getPkgName());
				LogUtil.d(TAG, "PkgName = " + appOprateSynObj.getPkgName());
				AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext(), R.style.AlterDialog);
				builder.setTitle(getString(R.string.app_name));
				builder.setMessage(getString(R.string.app_upgrade_success, appInfo.getAppName()));
				builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						AppUtils.openApp(getApplicationContext(), appInfo.getPkgName());
					}
				});
				builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {}
				});
				AlertDialog ad = builder.create();
				ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
				ad.setCanceledOnTouchOutside(true);
				ad.show();
			}

		}

	}

	public void handleProgress(DLFileInfo dLFileInfo) {}

	public void handleError(final DLFileInfo dLFileInfo, int errorCode, String errorInfo) {
		//		throw new ITVException(msg, code);
		String oprateResult = "";
		
		LogUtil.d(TAG, "handleError > start");
		
		//gy:delete state in downloading fragment
/*		String index = Integer.toHexString(dLFileInfo.getFileUrl().hashCode());
		ConfigUtil.clearURL(getApplicationContext(), index);*/
		
		LogUtil.d(TAG, "handleError > deleted state in downloading fragment");
		
		if (!TextUtils.isEmpty(dLFileInfo.getFileUrl())) {
			DownloadManager.getInstance(getApplicationContext()).deleteTaskForDownloadError(dLFileInfo);
		}
		
		LogUtil.d(TAG, "handleError > deleteTaskForDownloadError");
		
		oprateResult = "{code:-1, description: " + getString(R.string.app_install_failure) + "}";
		new Thread() {
			public void run() {
				AppOprateSynObj appOprateSynObj = null;
				for (AppOprateSynObj appSynObj : mAppOprateSynList) {
					if (appSynObj.getPkgName().equals(ConfigUtil.MINSHENG_KEY) || appSynObj.getPkgName().equals(dLFileInfo.getPkgName())) {
						appOprateSynObj = appSynObj;
						break;
					}
				}
				if (appOprateSynObj != null) {
					LogUtil.d(TAG, "handleError > unlock");
					synchronized (appOprateSynObj) {
						// 处理完成，唤醒等待的同步对象
						appOprateSynObj.notifyAll();
						//gy:从列表中删除
						mAppOprateSynList.remove(appOprateSynObj);
					}
				}
			};
		}.start();

		AppOprateSynObj appOprateSynObj = null;
		for (AppOprateSynObj appSynObj : mAppOprateSynList) {
			if (appSynObj.getPkgName().equals(ConfigUtil.MINSHENG_KEY) || appSynObj.getPkgName().equals(dLFileInfo.getPkgName())) {
				appOprateSynObj = appSynObj;
				break;
			}
		}
		
		if (appOprateSynObj != null) {
			appOprateSynObj.setOprateResult(oprateResult);
		}
		
		LogUtil.d(TAG, "handleError > end");
	}

	/**
	 * 增加下载任务
	 */
	private void addDLFile(DLFileInfo dLFileInfo) {
		LogUtil.d(TAG, "Add DL File() --> = " + dLFileInfo.getFilePath() + dLFileInfo.getFileName());
		DownloadHelper.addNewTask(AppOperate.this, dLFileInfo, new DownloadHelper.PreDownloadStatusListener() {

			@Override
			public void sdCardCannotWriteOrRead(int errorCode, String errorInfo) {
				Toast.makeText(AppOperate.this, "不能读写SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void notFoundSDCard(int errorCode, String errorInfo) {
				Toast.makeText(AppOperate.this, "没有SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void moreTaskCount(int errorCode, String errorInfo) {
				Toast.makeText(AppOperate.this, "任务列表已满", Toast.LENGTH_SHORT).show();
			}
		});
	}

	/**
	 * 
	 * 开始下载APK
	 * 
	 * @param apkurl
	 * @see [类、类#方法、类#成员]
	 */
	public void startDLAPK(String apkurl, String appName, String pkgName, String iconUrl, String appMD5) {
		DLFileInfo picFileInfo = new DLFileInfo();
		picFileInfo.setFilePath(ConfigUtil.FILE_PATH);
		picFileInfo.setFileUrl(apkurl);
		picFileInfo.setFileType("apk");
		picFileInfo.setPkgName(pkgName);
		picFileInfo.setFileName(appName + ".apk");
		picFileInfo.setIconUrl(iconUrl);
		picFileInfo.setMD5(appMD5);
		addDLFile(picFileInfo);
	}

	/**
	 * 第三方应用签名验证
	 * 
	 * @return -- true 合法应用<br>
	 *         -- false 非法应用
	 */
	private boolean checkSign() {
		String appPkgName = Confirmation.getProcessNameByPID(AppOperate.this, Binder.getCallingPid());
		LogUtil.v(TAG, "checkSign  AppPkgName --> " + appPkgName);
		if (appPkgName != null) {
			PackageInfo pkinfo = Confirmation.getPackageInfoByProcessName(AppOperate.this, appPkgName);
			CertificateInfo certificate = Confirmation.checkAPKSignature(AppOperate.this, pkinfo);
			if (certificate != null && certificate.islegal()) {
				return true;
			}
			else {
				LogUtil.e(TAG, "checkSign APP : " + appPkgName + "  ---> 应用合法性校验失败 ");
			}
		}
		if (ConfigUtil.isDebug)
			return true;
		else
			return false;
	}

	private String appopreate(String reqParam, AppOprateSynObj appOprateSynObj) {
		LogUtil.v(TAG, "appopreate reqParam-->" + reqParam);
		String result = "";
		if (checkSign() && !TextUtils.isEmpty(reqParam)) {
			AppOperateReqInfo info = new Gson().fromJson(reqParam, AppOperateReqInfo.class);
			if (info != null && !TextUtils.isEmpty(info.getAppId())) {
				result = appOpreate(info, appOprateSynObj);
			}
		}
		return result;
	}

	/**
	 * 
	 * App 操作接口
	 * 
	 * @param info
	 *            -- 请求参数，appId为custom开头，则是第三方应用更新，根据包名搜索文件并下载安装，<br>
	 *            其他情况根据appId直接查询下载地址并安装
	 * @param callAppPkgName
	 *            -- 调用接口的应用包名
	 * @return
	 */
	private String appOpreate(AppOperateReqInfo info, AppOprateSynObj appOprateSynObj) {
		synchronized (appOprateSynObj) {
			try {
				// 应用升级
				if (info.getAppId().contains("custom") && info.getOperate().equals("UPDATE")) {
					Bundle b = new Bundle();
					b.putString(HttpKeys.KEY_PACKAGENAME, appOprateSynObj.getPkgName());
					new AppUpdateTask(appOprateSynObj).execute(b);
				}
				// 如果为民生应用，直接安装
				else if (appOprateSynObj.getPkgName().equals(ConfigUtil.MINSHENG_KEY) && !TextUtils.isEmpty(info.getApkPath())) {
					installAPP(info.getApkPath(), info.getAppId(), appOprateSynObj);
				}
				// 处理 app 安装、删除、更新操作
				else {
					Bundle b = new Bundle();
					b.putInt(HttpKeys.KEY_APPID, Integer.parseInt(info.getAppId()));
					new AppCreateTask(appOprateSynObj).execute(b);
				}

				LogUtil.d(TAG, " --> appOpreate = " + " appOpreate has lost object lock");
				appOprateSynObj.wait();
				LogUtil.d(TAG, " --> appOpreate = " + " appOpreate has get object lock");

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return appOprateSynObj.getOprateResult();
	}

	/**
	 * 检测第三方应用是否需要更新
	 * 
	 * @return -- true 有更新<br>
	 *         -- false 无更新<br>
	 */

	private boolean appupdatecheck(final AppOprateSynObj appOprateSynObj) {

		if (checkSign()) {
			synchronized (appOprateSynObj) {
				try {
					new Thread() {
						public void run() {
							synchronized (appOprateSynObj) {
								try {
									String param = "";
									JSONArray element = new JSONArray();
									JSONObject item = new JSONObject();
									item.put("pkgName", appOprateSynObj.getPkgName());
									item.put("version", Confirmation.getVersion(getApplicationContext(), appOprateSynObj.getPkgName()));
									LogUtil.v(TAG, "Check APP Need Update Item-->" + item.toString());
									element.put(item);
									param = URLEncoder.encode(element.toString(), "UTF-8");
									//TODO 根据包名检测是否需要升级
									String isupdateApp = new HttpActions(getApplicationContext()).appIsUpdate(param);
									List<DownloadAppInfo> mListAppUpdate = JsonAnalytic.getInstance().anslyseAppResult(isupdateApp);
									for (int j = 0, len = mListAppUpdate.size(); j < len; j++) {
										LogUtil.v(TAG, "getNeedUpdateAppList() --> pkgName = " + mListAppUpdate.get(j).getPkgName() + " needUpdate = " + mListAppUpdate.get(j).isNeedUpdate());
										if (mListAppUpdate.get(j).isNeedUpdate()) {
											appOprateSynObj.setNeedUpdate(true);
										}
									}

								} catch (Exception e) {
									e.printStackTrace();
								} finally {
									appOprateSynObj.notifyAll();
								}
							}
						};
					}.start();
					LogUtil.d(TAG, " --> appOpreate = " + " appOpreate has lost object lock");
					appOprateSynObj.wait();
					LogUtil.d(TAG, " --> appOpreate = " + " appOpreate has get object lock");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return appOprateSynObj != null ? appOprateSynObj.isNeedUpdate() : false;
	}

	private void installAPP(final String apkPath, final String appId, final AppOprateSynObj appOprateSynObj) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				Object[] chmodRusult = BgInstallApk.excuteShellComm("chmod 777 " + apkPath);
				LogUtil.d(TAG, "chmodRusult = " + ((Boolean)chmodRusult[0]).booleanValue());
				
				Object[] installRst = BgInstallApk.installAppInBackGround(apkPath, "-r");
				boolean installResult = ((Boolean)installRst[0]).booleanValue();
				
				LogUtil.v(TAG, "installResult = " + installResult);
				String oprateResult;
				if (installResult) {
					oprateResult = "{appId: " + appId + " ,code: " + 0 + ", description: " + getString(R.string.app_install_success) + "}";
				}
				else {
					String errStr = (String)installRst[1]; 
					
					if(errStr.contains("INSUFFICIENT_STORAGE")){
						oprateResult = "{appId: " + appId + " ,code: " + -1 + ",  description: " + getString(R.string.app_install_failure_lackspace) + "}";
					}else if(errStr.contains(ComParams.ERROR_INVALID_PARAMETER)){
						oprateResult = "{appId: " + appId + " ,code: " + -1 + ",  description: " + getString(R.string.app_install_failure_invalid_para) + "}";
					}else{
						oprateResult = "{appId: " + appId + " ,code: " + -1 + ",  description: " + getString(R.string.app_install_failure) + "}";
					}
				}
				appOprateSynObj.setOprateResult(oprateResult);
				synchronized (appOprateSynObj) {
					// 处理完成，唤醒等待的同步对象
					appOprateSynObj.notifyAll();
				}
			}
		}).start();
	}

	/**
	 * 根据AppId 下载并安装推广APP
	 * 
	 * @author Emerson
	 */
	class AppCreateTask extends AsyncTask<Bundle, Integer, Bundle> {
		private AppOprateSynObj	appOprateSynObj;

		public AppCreateTask(AppOprateSynObj appOprateSynObj) {
			this.appOprateSynObj = appOprateSynObj;
		}

		public void UnlockTask() {
			this.appOprateSynObj.notifyAll();
		}

		@Override
		protected Bundle doInBackground(Bundle... params) {
			Bundle b = params[0];
			int appId = b.getInt(HttpKeys.KEY_APPID);
			try {
				if ((ConfigUtil.SessionKey == null && LoginMod.login(getApplicationContext())) || ConfigUtil.SessionKey != null) {
					b = appDLAndInstall(b, appId);
				}
			} catch (ITVException e) {
				new Thread() {
					public void run() {
						synchronized (appOprateSynObj) {
							// 处理完成，唤醒等待的同步对象
							appOprateSynObj.notifyAll();
						}
					};
				}.start();
			}
			return b;
		}

		@Override
		protected void onPostExecute(Bundle result) {
			super.onPostExecute(result);
		}

		private Bundle appDLAndInstall(Bundle b, int appId) throws ITVException {
			String appinfo = new HttpActions(getApplicationContext()).getAppInfo(appId, "0");
			LogUtil.v(TAG, "appinfo = " + appinfo);
			AppDetailInfo mAppDetailInfo = JsonAnalytic.getInstance().anslyseAppDetailResult(appinfo);

			LogUtil.v(TAG, "AppDetailInfo = " + mAppDetailInfo.getAppName());
			if (mAppDetailInfo != null && mAppDetailInfo.getPrice() == 0 && mAppDetailInfo.getDiscountPrice() == 0) {
				String dlApp = new HttpActions(getApplicationContext()).downApp(0, "" + appId, 0);
				LogUtil.v(TAG, "getAppUrl result-->" + dlApp);
				if (!TextUtils.isEmpty(dlApp)) {
					String appUrl = JsonAnalytic.getInstance().anslyseAppDLUrlResult(dlApp);
					String appMD5 = JsonAnalytic.getInstance().anslyseAppDLMD5Result(dlApp);
					startDLAPK(appUrl, mAppDetailInfo.getAppName(), mAppDetailInfo.getPackageName(), mAppDetailInfo.getIconUrl(), appMD5);
				}
			}
			else {
				// 收费应用跳转到支付页面getString(R.string.aidl_pay_app); code =  2 
				throw new ITVException(getString(R.string.aidl_pay_app), 2);
			}

			return b;
		}

	}

	/**
	 * 应用更新下载安装
	 * 
	 * @author Emerson
	 */
	private class AppUpdateTask extends AsyncTask<Bundle, Integer, Bundle> {
		private AppInfo			mHandlerAppInfo;
		private AppOprateSynObj	appOprateSynObj;

		public AppUpdateTask(AppOprateSynObj appOprateSynObj) {
			this.appOprateSynObj = appOprateSynObj;
		}

		public void UnlockTask() {
			this.appOprateSynObj.notifyAll();
		}

		@Override
		protected Bundle doInBackground(Bundle... params) {
			Bundle b = params[0];
			String appPkgName = b.getString(HttpKeys.KEY_PACKAGENAME);
			try {
				if ((ConfigUtil.SessionKey == null && LoginMod.login(getApplicationContext())) || ConfigUtil.SessionKey != null) {
					appUpdate(appPkgName);
				}
			} catch (ITVException e) {
				new Thread() {
					public void run() {
						synchronized (appOprateSynObj) {
							// 处理完成，唤醒等待的同步对象
							appOprateSynObj.notifyAll();
						}
					};
				}.start();
			}
			return b;
		}

		@Override
		protected void onPostExecute(Bundle result) {
			super.onPostExecute(result);
		}

		private void appUpdate(String appPkgName) throws ITVException {

			synchronized (appOprateSynObj) {
				try {
					String param = "";
					JSONArray element = new JSONArray();
					JSONObject item = new JSONObject();
					try {
						item.put("pkgName", appPkgName);
						item.put("version", Confirmation.getVersion(getApplicationContext(), appPkgName));
						LogUtil.v(TAG, "Check APP Need Update Item-->" + item.toString());
						element.put(item);
						param = URLEncoder.encode(element.toString(), "UTF-8");
						String isupdateApp = new HttpActions(getApplicationContext()).appIsUpdate(param);
						List<AppInfo> mListAppUTemp = JsonAnalytic.getInstance().anslyseUpdateAppResult(isupdateApp);
						for (int j = 0, len = mListAppUTemp.size(); j < len; j++) {
							LogUtil.v(TAG, "getNeedUpdateAppList() --> pkgName = " + mListAppUTemp.get(j).getPkgName() + " needUpdate = " + mListAppUTemp.get(j).isNeedUpdate());
							if (mListAppUTemp.get(j).isNeedUpdate()) {
								appOprateSynObj.setNeedUpdate(true);
								mHandlerAppInfo = mListAppUTemp.get(j);
								break;
							}
						}
						if (appOprateSynObj.isNeedUpdate()) {
							String dlApp = new HttpActions(getApplicationContext()).downApp(0, "" + mHandlerAppInfo.getAppId(), 0);
							LogUtil.v(TAG, "getAppUrl result-->" + dlApp);
							if (!TextUtils.isEmpty(dlApp)) {
								String appUrl = JsonAnalytic.getInstance().anslyseAppDLUrlResult(dlApp);
								String appMD5 = JsonAnalytic.getInstance().anslyseAppDLMD5Result(dlApp);
								startDLAPK(appUrl, mHandlerAppInfo.getAppName(), mHandlerAppInfo.getPkgName(), mHandlerAppInfo.getIconUrl(), appMD5);
							}
						}

					} catch (JSONException e) {
						e.printStackTrace();
					} catch (ITVException e) {
						e.printStackTrace();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}
}
